package com.dropdb.demo.controller.wx;

import com.dropdb.demo.bean.User;
import com.dropdb.demo.bean.enumeration.ErrorReason;
import com.dropdb.demo.bean.vo.BaseRespVO;
import com.dropdb.demo.service.SearchService;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("wx/search")
public class WxSearchController {
    @Autowired
    SearchService searchService;

    /**
     * 搜索首页
     * @return
     */
    @RequestMapping(value = "index", method = RequestMethod.GET)
    public BaseRespVO indexOfSearch() {
        Subject subject = SecurityUtils.getSubject();
        User user = (User) subject.getPrincipal();
        Integer id = null;
        if (user != null) id = user.getId();
        HashMap<String,Object> index = searchService.getIndexOfSearch(id);
        return BaseRespVO.ok(index);
    }

    @RequestMapping(value = "helper", method = RequestMethod.GET)
    public BaseRespVO searchHelper(String keyword) {
        List<String> helpers = searchService.searchHelper(keyword);
        return BaseRespVO.ok(helpers);
    }

    /**
     * 需要user信息
     */
    @RequestMapping(value = "clearhistory", method = RequestMethod.POST)
    public BaseRespVO clearHistory(@RequestBody Map<String,Object> map) {
        User user =  (User)SecurityUtils.getSubject().getPrincipal();
        if (user == null) return BaseRespVO.error(ErrorReason.UN_LOGIN.getCode(),ErrorReason.UN_LOGIN.getReason());
        searchService.clearHistory(user.getId());
        return BaseRespVO.ok();
    }
}
